<template>
  <view class="container">
    <u-navbar
      :is-fixed="true"
      :border-bottom="false"
      :is-back="true"
      :background="{ background: '#5697F1' }"
      :title="title"
      title-color="#000"
    >
    </u-navbar>
    <u-popup :mask-close-able="true" width="650" v-model="isOpen" mode="center">
      <view class="modal">
        <view>途径详情</view>
        <view class="each-row" v-for="(l, index) in lines" :key="index">
          <view>{{ l.name }}</view>
          <view>
            <text v-if="index !== lines.length - 1">发车时间</text>
            <text v-if="index == lines.length - 1">到达时间</text>
            {{ l.startTime }}</view>
        </view>
      </view>
    </u-popup>
    <!-- <view class="station">
      <view>{{station.start}}</view>
      <image class="img" src="/static/images/arrow.svg"></image>
      <view>{{station.end}}</view>
    </view> -->
    <view class="date">
      <view @click="showCan" class="row">
        日期：{{station.date}}>
      </view>
      <u-calendar :min-date="today" :max-date="maxDate" @change="chooseDate" v-model="show" :mode="mode"></u-calendar>
    </view>

    <view class="tickets">
      <view class="each" @click="doConfirm(ticket)" v-for="(ticket, index) in tickets" :key="index">
        <view class="row">
          <view class="block">
            <view class="cn">发车时间</view>
            <view>{{ticket.startTime}}</view>
          </view>
          <view class="block">
            <view class="cn">{{ticket.name}}</view>
            <view style="font-size: 22rpx;margin-top: 20rpx;" @click.stop="showLines(ticket)">{{ticket.totalTime}}
              <u-icon name="arrow-down-fill"></u-icon>
            </view>
          </view>
          <view class="block">
            <view class="cn">到达时间</view>
            <view>{{ticket.endTime}}</view>
          </view>
        </view>
        <view class="seats">
          <view class="each-s" v-for="(seat, sIndex) in ticket.seats" :key="sIndex">{{seat.name}}: {{seat.cnt}}张</view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import moment from 'moment'
import { getTrain } from '../../api/system/api'
export default {
  data() {
    return {
      station: {},
      title: '',
      mode: 'date',
      show: false,
			today: moment().format('YYYY-MM-DD'),
			maxDate: moment().add(14, 'days').format('YYYY-MM-DD'),
      tickets: [],
      isOpen: false,
      lines: [],
      isGQ: false,
      option: {}
    };
  },
  onLoad(option) {
    // 接收home 或者 detial 跳转过来的参数
    this.station = option
    // 如果有option.option说明是ditail跳转过来 代表是改签
    if (option.option) {
      this.isGQ = true
      this.option = JSON.parse(option.option)
    }
    console.log(this.option)
    // 改签的顶部标题处理
    this.title = this.isGQ ? this.station.start + '-' + this.station.end + '（改签）' : this.station.start + '-' + this.station.end
    this.getTickets()
  },
  methods: {
		showCan() {
			this.show = true
		},
    // 选择日期并查询车票
		chooseDate(e) {
			this.station.date = e.result
      this.getTickets()
		},
    // 跳转至确认订单页面 并携带参数
    doConfirm(ticket) {
			this.$u.route('/pages/interest/confirm', {
        ticket: JSON.stringify({
          ...ticket,
          start: this.station.start,
          end: this.station.end,
          tickTime: this.station.date,
          option: this.option
        })
			})
    },
    // 获取车票
    getTickets() {
      // 获取满足条件的车次
      getTrain({
        start: this.station.start,
        end: this.station.end,
        date: this.station.date
      }).then(res => {
        if (res.code === 200) {
          // 车票日期
          const ymd = moment(this.station.date).format('YYYY-MM-DD')
          // 只看当天还未发车的车次
          this.tickets = res.data.data.filter(v => moment(`${ymd} ${v.startTime}`).valueOf() > moment().valueOf())
          this.tickets.forEach((v, i) => {
            // 转成json
            this.tickets[i].line = JSON.parse(v.line)
            this.tickets[i].seats = JSON.parse(v.seats)
            // 计算结束时间
            let endTime = ''
            let minutes = 0
            // 处理结束时间   后续哪些站 加上各自站的time

            // 分为起始站点是车次的起始站点
            if (v.startStation === this.station.start) {
              let index = this.tickets[i].line.findIndex(v => v.station === this.station.end)
              for (let i2 = 0;i2 <= index; i2++) {
                // 统计总时长
                minutes += this.tickets[i].line[i2].time
              }
              endTime = moment(`2022-10-01 ${v.startTime}`).add(minutes, 'minutes').format('HH:mm:ss')
              this.tickets[i].endTime = endTime;
            } else {
              // 起始站是车次的途径站点
              let indexS = this.tickets[i].line.findIndex(v => v.station === this.station.start)
              let indexE = this.tickets[i].line.findIndex(v => v.station === this.station.end)
              let startTime = ''
              let endTime = ''
              let minutesS = 0
              let minutesE = 0
              for (let i2 = 0;i2 <= indexS; i2++) {
                minutesS += this.tickets[i].line[i2].time
              }
              for (let i2 = 0;i2 <= indexE; i2++) {
                minutesE += this.tickets[i].line[i2].time
              }
              // 处理开始时间
              startTime = moment(`2022-10-01 ${v.startTime}`).add(minutesS, 'minutes').format('HH:mm:ss')
              // 处理结束时间
              endTime = moment(`2022-10-01 ${v.startTime}`).add(minutesE, 'minutes').format('HH:mm:ss')
              this.tickets[i].startTime = startTime;
              this.tickets[i].endTime = endTime;
            }
            // 处理总时长
            let totalTime = ''
            if (moment(`2022-01-01 ${this.tickets[i].endTime}`).valueOf() < moment(`2022-01-01 ${this.tickets[i].startTime}`).valueOf()) {
              totalTime = moment(`2022-01-02 ${this.tickets[i].endTime}`).diff(moment(`2022-01-01 ${this.tickets[i].startTime}`), 'minutes' )
            } else {
              totalTime = moment(`2022-01-01 ${this.tickets[i].endTime}`).diff(moment(`2022-01-01 ${this.tickets[i].startTime}`), 'minutes' )
            }
            this.tickets[i].totalTime = this.handleTotal(totalTime)
          })
          // 排序 按发车时间的顺序排序
          this.tickets = this.tickets.sort((a, b) => {
            return moment(this.station.date + ' ' + a.startTime).valueOf() - moment(this.station.date + ' ' + b.startTime).valueOf()
          })
        }
      })
    },
    // 处理总运行时间
    handleTotal(time) {
      let minute = time % 60
      let hour = (time - minute) / 60
      // 超过一小时
      if (hour > 0) {
        return `${hour}小时${minute}分钟`
      } else {
        // 不超过只显示分钟
        return `${minute}分钟`
      }
    },
    // 查看途径站点
    showLines(row) {
      console.log(row)
      let lines = []
      let indexS = 0
      let indexE = 0
      // 也是分为起始站是不是车次管理的起始站
      if (row.startStation === this.station.start) {
        lines.push({
          name: row.startStation,
          startTime: row.startTime
        })
      } else {
        indexS = row.line.findIndex(v => v.station === this.station.start)
      }
      indexE = row.line.findIndex(v => v.station === this.station.end)
      // 然后将起始到终点之间的站点放在lines数组里面
      for (let i = indexS;i <= indexE; i++) {
        lines.push({
          name: row.line[i].station,
          startTime: lines.length ? moment(`2022-10-01 ${lines[lines.length - 1].startTime}`).add(row.line[i].time, 'minutes').format('HH:mm:ss') : moment(`2022-10-01 ${row.startTime}`).add(row.line[i].time, 'minutes').format('HH:mm:ss')
        })
      }
      this.lines = lines
      // 打开查看途径站点的模态框
      this.isOpen = true
      
    }
  },
};
</script>

<style lang="scss" scoped>
.container {
  background-color: #f1ebeb;
  min-height: 100vh;
  overflow: hidden;
  padding: 2rpx;
}
.station {
  display: flex;
  width: 50%;
  margin: 0 auto;
  align-items: center;
  font-size: 40rpx;
  justify-content: space-around;
  font-weight: bold;
  .img {
    width: 50rpx;
    height: 50rpx;
  }
}
.date {
	display: flex;
	padding: 30rpx 60rpx 0 60rpx;
	font-size: 30rpx;
	justify-content: space-between;

	.img {
		width: 60rpx;
		height: 60rpx;
	}
}
.row {
  margin: 0 auto;
	width: 50%;
  text-align: center;
}
.tickets {
  padding: 30rpx;
  .each {
    background: #fff;
    border-radius: 12rpx;
    padding: 12rpx;
    margin-bottom: 30rpx;

    .row {
      display: flex;
      width: 100%;
      justify-content: space-between;
      font-size: 30rpx;
      font-weight: bold;
      padding: 20rpx 0;
      border-bottom: 1rpx solid #e4dada;
      .cn {
        font-size: 20rpx;
        margin-bottom: 10rpx;
      }
    }
    .seats {
      display: flex;
      flex-wrap: wrap;
      .each-s {
        background: #fff;
        border-radius: 12rpx;
        padding: 12rpx;
        width: 30%;
      }
    }
  }
}
.modal {
  padding: 30rpx;
  margin: auto;
  
  .each-row {
    display: flex;
    align-items: center;
    gap: 30rpx;
    line-height: 60rpx;
  }
}
</style>
